package org.hairball.cli;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class CommandLineParser {
    private Map<String, Option> optionMap;

    public CommandLineParser(Option... options) {
        optionMap = new HashMap<String, Option>();
        for (Option option : options) {
            optionMap.put(option.getArgName(), option);
        }
    }

    public String usage() {
        StringBuilder builder = new StringBuilder();

        for (String argName : optionMap.keySet()) {
            Option option = optionMap.get(argName);
            builder.append(argName).append("\t\t");
            builder.append(option.getDescription());
            builder.append("\n");
        }
        return builder.toString();
    }

    public Map<String, String> parse(String args[]) throws CommandLineParseException {
        HashMap<String, String> values = new HashMap<String, String>();
        HashSet<String> parsedValues = new HashSet<String>();

        for (int i = 0; i < args.length; i += 2) {
            String argName = args[i];
            String argValue = args[i + 1];
            if (optionMap.containsKey(argName)) {
                values.put(argName, argValue);
                parsedValues.add(argName);
            } else {
                throw new CommandLineParseException("Argument " + argName + " is not supported", usage());
            }
        }

        for (String argName : optionMap.keySet()) {
            if (!parsedValues.contains(argName)) {
                Option option = optionMap.get(argName);

                if (option.hasDefault()) {
                    values.put(argName, option.getDefaultValue());
                } else {
                    throw new CommandLineParseException("Required argument '" + argName + "' was not specified", usage());
                }
            }
        }

        return values;
    }
}
